package com.jz.community.moduleshoppingguide.neighbor.ui.fragment;


import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.jz.community.basecomm.base.BaseMvpLoadFragment;
import com.jz.community.basecomm.constant.AppConstants;
import com.jz.community.basecomm.glideConfig.GlideApp;
import com.jz.community.basecomm.utils.BaseSpUtils;
import com.jz.community.basecomm.utils.Preconditions;
import com.jz.community.basecomm.utils.WpToast;
import com.jz.community.basecomm.utils.eventbus.AppEvent;
import com.jz.community.basecomm.utils.eventbus.EventConfig;
import com.jz.community.commview.callback.EmptyCallback;
import com.jz.community.commview.callback.ErrorCallback;
import com.jz.community.commview.callback.LoadingCallback;
import com.jz.community.moduleshoppingguide.R;
import com.jz.community.moduleshoppingguide.R2;
import com.jz.community.moduleshoppingguide.neighbor.bean.BlogsListBean;
import com.jz.community.moduleshoppingguide.neighbor.bean.CircleMessageBean;
import com.jz.community.moduleshoppingguide.neighbor.presenter.NeighborMinePresenter;
import com.jz.community.moduleshoppingguide.neighbor.task.CommentReplyTask;
import com.jz.community.moduleshoppingguide.neighbor.ui.NeighborMineView;
import com.jz.community.moduleshoppingguide.neighbor.ui.activity.NeighborMainActivity;
import com.jz.community.moduleshoppingguide.neighbor.ui.adapter.RelCircleDynamicAdapter;
import com.jz.community.moduleshoppingguide.neighbor.ui.view.DialogInput;
import com.jz.community.moduleshoppingguide.neighbor.ui.view.NeighborHead;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;

import butterknife.BindView;

public class NeighborMineFragment extends BaseMvpLoadFragment<NeighborMineView.View, NeighborMinePresenter> implements NeighborMineView.View, RelCircleDynamicAdapter.OnCircleItemClickListener, OnRefreshListener, BaseQuickAdapter.RequestLoadMoreListener {

    @BindView(R2.id.cf_dynamic_recyclerView)
    RecyclerView cfDynamicRecyclerView;
    @BindView(R2.id.cf_dynamic_refresh)
    SmartRefreshLayout cfDynamicRefresh;

    RelCircleDynamicAdapter adapter;
    DialogInput dialogInput;
    private int page = 0;
    private int size = 10;
    private String circleId;
    private boolean needRefresh = false;
    NeighborHead head;

    @Override
    protected int getContentViewLayoutID() {
        return R.layout.module_shoppingguide_fragment_neighbor_mine;
    }

    @Override
    protected NeighborMinePresenter createPresenter() {
        return new NeighborMinePresenter(this);
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        adapter = new RelCircleDynamicAdapter(new ArrayList<>());
        cfDynamicRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
        cfDynamicRecyclerView.setAdapter(adapter);
        cfDynamicRefresh.setOnRefreshListener(this);
        cfDynamicRefresh.setEnableLoadMore(false);
        adapter.setOnLoadMoreListener(this, cfDynamicRecyclerView);
    }


    @Override
    protected void addListener() {
        getActivity().getWindow().getDecorView().getViewTreeObserver().addOnGlobalLayoutListener(() -> handleWindowChange());

        mBaseLoadService.setCallBack(LoadingCallback.class, (context, view) -> {
            ImageView mIvLoading = view.findViewById(R.id.loading_img);
            GlideApp.with(getActivity())
                    .asGif()
                    .load(R.drawable.loading_default)
                    .into(mIvLoading);

        });
        mBaseLoadService.setCallBack(ErrorCallback.class, (context, view) -> {
            ImageView mIvError = view.findViewById(R.id.error_img);
            mIvError.setImageResource(R.mipmap.error_default);
        });

        mBaseLoadService.setCallBack(EmptyCallback.class, (context, view) -> {
            ImageView mIvEmpty = view.findViewById(R.id.empty_img);
            mIvEmpty.setImageResource(R.mipmap.empty_default);
            TextView textView = view.findViewById(R.id.empty_tv);
            textView.setText("您还没有加入圈子,请先加入一个圈子>");
            textView.setOnClickListener(v -> ((NeighborMainActivity) getActivity()).jumpNeighborNear());
        });

    }


    @Override
    protected void initDatas() {
        circleId = (String) getArguments().get("circleId");
        if (!TextUtils.isEmpty(circleId)) {
            getCircleMsg();
        } else {
            mBaseLoadService.showCallback(EmptyCallback.class);
        }
    }

    private void getCircleMsg() {
        String com_lat = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lat;
        String com_lon = BaseSpUtils.getInstance().getCurrentCommuity(getActivity()).lon;
        mPresenter.initNeighborMsg(circleId, com_lat, com_lon);
    }

    @Override
    protected void initLazy(@Nullable Bundle savedInstanceState) {
        super.initLazy(savedInstanceState);
        page = 0;
        if (!Preconditions.isNullOrEmpty(circleId)) {
            mPresenter.circleDynamic(circleId, page, size, AppConstants.ONREFRESH);
        }
    }


    @Override
    public void showCircleDynamic(BlogsListBean blogsListBean, int type) {
        mBaseLoadService.showSuccess();
        adapter.loadMoreEnd();
        cfDynamicRefresh.finishRefresh();
        if (blogsListBean.get_embedded().getContent() != null && blogsListBean.get_embedded().getContent().size() > 0) {
            if (type == AppConstants.ONREFRESH) {
                adapter.setNewData(blogsListBean.get_embedded().getContent());
            } else {
                adapter.addData(blogsListBean.get_embedded().getContent());
            }
            adapter.setListener(this);
        }
    }

    @Override
    public void showError(String s) {
        adapter.loadMoreEnd();
        cfDynamicRefresh.finishRefresh();
    }

    @Override
    public void onItemAddPraiseClick(View view, int position, BlogsListBean.EmbeddedBean.ContentBean item) {
        mPresenter.putFavorite(item.getId(), item);
    }

    @Override
    public void favoriteOk(BlogsListBean.EmbeddedBean.ContentBean.FavoriteBean favoriteBean, BlogsListBean.EmbeddedBean.ContentBean item) {
        if (item.getFavorite() != null && item.getFavorite().size() > 0) {
            int j = -1;
            for (int i = 0; i < item.getFavorite().size(); i++) {
                if (item.getFavorite().get(i).getUserId().equals(favoriteBean.getUserId())) {
                    j = i;
                    break;
                }
            }
            if (j != -1) {
                item.getFavorite().remove(item.getFavorite().get(j));
            } else {
                item.getFavorite().add(favoriteBean);
            }
            adapter.notifyDataSetChanged();
        } else {
            item.getFavorite().add(favoriteBean);
            adapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemAddCommentClick(View v, int position, BlogsListBean.EmbeddedBean.ContentBean item) {
        int itemBottomY = getCoordinateY(v) + v.getHeight();
        dialogInput = new DialogInput(getActivity());
        dialogInput.show();
        //输入框根据位置弹出
        v.postDelayed(() -> {
            RelativeLayout llCommentInput = dialogInput.getInputView();
            int y = getCoordinateY(llCommentInput);
            if (position == adapter.getData().size() - 1) {
                BlogsListBean.EmbeddedBean.ContentBean c = new BlogsListBean.EmbeddedBean.ContentBean();
                c.setType(0);
                adapter.getData().add(c);
                adapter.bottomHeight = llCommentInput.getHeight();
                adapter.notifyDataSetChanged();
            }
            //滑动 RecyclerView，是对应 item 底部和输入框顶部对齐
            cfDynamicRecyclerView.smoothScrollBy(0, itemBottomY - y);
        }, 300);
        //提交评论
        dialogInput.getCommentBtn().setOnClickListener(v1 -> {
            if (!TextUtils.isEmpty(dialogInput.getEditString())) {
                new CommentReplyTask(getActivity(), o -> {
                    if (o != null) {
                        BlogsListBean.EmbeddedBean.ContentBean.ReplyVosBean replyVosBean = (BlogsListBean.EmbeddedBean.ContentBean.ReplyVosBean) o;
                        item.getReplyVos().add(replyVosBean);
                        adapter.notifyDataSetChanged();
                        dialogInput.dismiss();
                    }
                }).execute(item.getId() + "", dialogInput.getEditString(), BaseSpUtils.getInstance().getUserBaseInfo(getActivity()).getNickname(), BaseSpUtils.getInstance().getUserBaseInfo(getActivity()).getUid() + "", "1");
            }
        });
    }

    @Override
    public void onItemPutCommentPosition(View v, int position, int rvPosition, BlogsListBean.EmbeddedBean.ContentBean item) {
        int itemBottomY = getCoordinateY(v) + v.getHeight();
        dialogInput = new DialogInput(getActivity());
        dialogInput.show();
        //输入框根据位置弹出
        v.postDelayed(() -> {
            RelativeLayout llCommentInput = dialogInput.getInputView();
            int y = getCoordinateY(llCommentInput);
            if (rvPosition == adapter.getData().size() - 1) {
                BlogsListBean.EmbeddedBean.ContentBean c = new BlogsListBean.EmbeddedBean.ContentBean();
                c.setType(0);
                adapter.getData().add(c);
                adapter.bottomHeight = llCommentInput.getHeight();
                adapter.notifyDataSetChanged();
            }
            //滑动 RecyclerView，是对应 item 底部和输入框顶部对齐
            cfDynamicRecyclerView.smoothScrollBy(0, itemBottomY - y);
        }, 300);
        String userId = BaseSpUtils.getInstance().getUserId(getActivity()) + "";
        if (!userId.equals(item.getReplyVos().get(position).getReUserId())) {
            //提交评论
            dialogInput.getCommentBtn().setOnClickListener(v1 -> {
                if (!TextUtils.isEmpty(dialogInput.getEditString())) {
                    new CommentReplyTask(getActivity(), o -> {
                        if (o != null) {
                            BlogsListBean.EmbeddedBean.ContentBean.ReplyVosBean replyVosBean = (BlogsListBean.EmbeddedBean.ContentBean.ReplyVosBean) o;
                            item.getReplyVos().add(replyVosBean);
                            adapter.notifyDataSetChanged();
                            dialogInput.dismiss();
                        }
                    }).execute(item.getId() + "", dialogInput.getEditString(), item.getReplyVos().get(position).getReNickName(), item.getReplyVos().get(position).getReUserId() + "", "1");
                }
            });
        } else {
            WpToast.l(getActivity(), "自己不能给自己回复!");
        }
    }

    @Override
    public void onItemClickListener(View view, int position, BlogsListBean.EmbeddedBean.ContentBean item) {

    }

    @Override
    public void onItemClickHeadImage(View view, int position, BlogsListBean.EmbeddedBean.ContentBean item) {

    }

    private int getCoordinateY(View view) {
        int[] coordinate = new int[2];
        view.getLocationOnScreen(coordinate);
        return coordinate[1];
    }


    private void handleWindowChange() {
        Rect rect = new Rect();
        getActivity().getWindow().getDecorView().getWindowVisibleDisplayFrame(rect);
        int displayHeight = rect.bottom - rect.top;
        int totalHeight = getActivity().getWindow().getDecorView().getHeight();
        //显示内容的高度和屏幕高度比大于 0.8 时，dismiss dialog
        if ((float) displayHeight / totalHeight > 0.8) {
            //0.8只是一个大致的比例，可以修改
            if (null != dialogInput && dialogInput.isShowing()) {
                dialogInput.dismiss();
                //如果添加了空白 item ，移除空白 item
                if (adapter.getData().get(adapter.getData().size() - 1).getType() == 0) {
                    adapter.getData().remove(adapter.getData().size() - 1);
                    adapter.notifyDataSetChanged();
                }
            }
        }
    }


    @Override
    public void setNeighborMsgData(CircleMessageBean entity) {
        initHeadData(entity);
        page = 0;
        if (!Preconditions.isNullOrEmpty(circleId)){
            mPresenter.circleDynamic(circleId, page, size, AppConstants.ONREFRESH);
        }
    }

    private void initHeadData(CircleMessageBean circleBean) {
        if (adapter.getHeaderLayoutCount() == 0) {
            head = new NeighborHead(getActivity(), cfDynamicRecyclerView);
            head.setData(circleBean);
            adapter.addHeaderView(head.getHeadView());
        } else {
            head.setData(circleBean);
        }
    }


    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if (isVisibleToUser && needRefresh) {
            mBaseLoadService.showCallback(LoadingCallback.class);
            getCircleMsg();
            needRefresh = false;
        }
    }


    @Override
    protected void clickError() {
        getCircleMsg();
    }


    /**
     * @param message
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void EventBus(AppEvent message) {
        if (message.tag == EventConfig.REFRESH_MINE_CIRCLE) {
            if (message.num == 0) {
                mBaseLoadService.showCallback(EmptyCallback.class);
            } else if (message.num == 1) {
                getCircleMsg();
            }
        } else if (message.tag == EventConfig.DELAYED_REFRESH_MINE_CIRCLE) {
            needRefresh = true;
            circleId = message.str;
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onRefresh(RefreshLayout refreshLayout) {
        getCircleMsg();
    }

    @Override
    public void onLoadMoreRequested() {
        page++;
        if (!Preconditions.isNullOrEmpty(circleId)) {
            mPresenter.circleDynamic(circleId, page, size, AppConstants.ONLOADMORE);
        }
    }
}
